package com.meatball.authorization.config.handler

import com.alibaba.fastjson.JSON
import com.meatball.core.config.BaseResponse
import com.meatball.core.config.UNAUTHORIZED
import com.meatball.core.config.USERNAME_OR_PASSWORD_INCORRECT
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.slf4j.LoggerFactory
import org.springframework.security.authentication.BadCredentialsException
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.AuthenticationEntryPoint

/**
 * TODO 检测到未登录的时候，这里返回json的应答，而不是跳转到登录页面
 *
 * @author 张翔宇
 * @since 2024年3月25日
 */
class CustomAuthenticationEntryPoint : AuthenticationEntryPoint {
    companion object {
        private val logger = LoggerFactory.getLogger(CustomAuthenticationEntryPoint::class.java)
    }

    override fun commence(
        request: HttpServletRequest?,
        response: HttpServletResponse?,
        authException: AuthenticationException?)
    {
        logger.error("角色权限报错：$authException")
        response?.let {
            it.status = HttpServletResponse.SC_FORBIDDEN
            it.contentType = "application/json;charset=UTF-8"

            val message = when(authException) {
                is BadCredentialsException -> USERNAME_OR_PASSWORD_INCORRECT
                else -> UNAUTHORIZED
            }

            it.writer.write(JSON.toJSONString(BaseResponse.error(HttpServletResponse.SC_FORBIDDEN, message)))
        }
    }
}